package com.xuxueli.applyModules.utils.testqcode;
import com.lowagie.text.pdf.Barcode128;
import com.xuxueli.applyModules.exception.ErrorException;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;

/**
 * 测试生成条形码 success
 */
public class BarcodeUtil {

    public static void main(String[] args) {
        createBarcode("test","D:\\data\\images\\13b10138e40442fbbe443bc7b887a7b4.jpg");
    }

    public static void createBarcode(String listNo, String imagePath) {
        Font font = new Font("", Font.PLAIN, 12);
        Barcode128 barcode128 = new Barcode128();
        barcode128.setCode(listNo);
        Image pdfImg = barcode128.createAwtImage(Color.black, Color.white);
        BufferedImage img = new BufferedImage(pdfImg.getWidth(null), pdfImg.getHeight(null), BufferedImage.TYPE_INT_RGB);
        Graphics g = img.getGraphics();
//        g.fillRect(0, 0, pdfImg.getWidth(null), pdfImg.getHeight(null) + HEIGHT_SPACE);
//        FontRenderContext fontRenderContext = ((Graphics2D)g).getFontRenderContext();
//        // 图片横坐标开始位置
//        int startX = 0;
//        // 图片纵坐标开始位置
//        int imageStartY = 0;
//        int stringStartY = pdfImg.getHeight(null) + HEIGHT_SPACE;// 条形码（文字）开始位置
//        int codeWidth = (int) font.getStringBounds(listNo, fontRenderContext).getWidth();
        g.drawImage(pdfImg, 0, 0, Color.white, null);
//        AttributedString ats = new AttributedString(listNo);
//        ats.addAttribute(TextAttribute.FONT, font, 0, listNo.length());
//        AttributedCharacterIterator iter = ats.getIterator();
//        g.setColor(Color.BLACK);// 绘制条形码（文字）
//        g.drawString(iter,  + (pdfImg.getWidth(null) - codeWidth) / 2 , stringStartY);
//        g.dispose();
        try {
            ImageIO.write(img, "PNG", new File(imagePath));
        } catch (Exception e) {
            throw new ErrorException(400, "生成条形码出错！");
        }
    }
}